package org.vacoor.nothing.misc.express;

import org.vacoor.nothing.common.codec.Base64;
import org.vacoor.nothing.common.util.Bytes;
import org.vacoor.nothing.common.util.IOUtils;
import org.vacoor.nothing.misc.express.usps.api.Usps;
import org.vacoor.nothing.misc.express.usps.api.data.type.UspsFirstClassMailType;
import org.vacoor.nothing.misc.express.usps.api.print.SignatureConfirmationlRequest;
import org.vacoor.nothing.misc.express.usps.api.rate.v4.RatePackage;
import org.vacoor.nothing.misc.express.usps.api.rate.v4.Service;
import org.vacoor.nothing.misc.express.usps.api.rate.v4.Size;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

/**
 * Created by Administrator on 2014/10/9.
 */
public class UspsDemo {
    public static void main(String[] args) throws IOException, NoSuchAlgorithmException, KeyManagementException, ParserConfigurationException, SAXException, XPathExpressionException {
        String serviceUrl = "https://secure.shippingapis.com/ShippingAPI.dll";
        String api = "ExpressMailLabelCertify";
//        String api = "ExpressMailLabel";
        String xml = "<ExpressMailLabelCertifyRequest  USERID=\"034I2GLO7047\" PASSWORD=\"089KU88WB902\">\n" +
                "    <Option />\n" +
                "    <Revision>2</Revision>\n" +
                "    <EMCAAccount />\n" +
                "    <EMCAPassword />\n" +
                "    <ImageParameters />\n" +
                "    <FromFirstName>Adam</FromFirstName>\n" +
                "    <FromLastName>Smith</FromLastName>\n" +
                "    <FromFirm/>\n" +
                "<FromAddress1>RM 2100</FromAddress1>\n" +
                "<FromAddress2>475 L’Enfant Plaza SW</FromAddress2>\n" +
                "<FromCity>Washington</FromCity>\n" +
                "<FromState>DC</FromState>\n" +
                "<FromZip5>20260</FromZip5>\n" +
                "<FromZip4/>\n" +
                "<FromPhone>2125551234</FromPhone>\n" +
                "<ToFirstName>中文</ToFirstName>\n" +
                "<ToLastName>Dickens</ToLastName>\n" +
                "<ToFirm>XYZ Corporation</ToFirm>\n" +
                "<ToAddress1>RM 21000</ToAddress1>\n" +
                "<ToAddress2>475 L’Enfant Plaza SW</ToAddress2>\n" +
                "<ToCity>Washington</ToCity>\n" +
                "<ToState>DC</ToState>\n" +
                "<ToZip5>20212</ToZip5>\n" +
                "<ToZip4 />\n" +
                "<ToPhone>2125551234</ToPhone>\n" +
                "<WeightInOunces>105</WeightInOunces>\n" +
                "<FlatRate/>\n" +
                "<SundayHolidayDelivery/>\n" +
                "<StandardizeAddress/>\n" +
                "<WaiverOfSignature/>\n" +
                "<NoHoliday/>\n" +
                "<NoWeekend/>\n" +
                "<SeparateReceiptPage/>\n" +
                "<POZipCode>20212</POZipCode>\n" +
                "<FacilityType>DDU</FacilityType>\n" +
//                "<ImageType>PDF</ImageType>\n" +
                "<ImageType>TIF</ImageType>\n" +
                "<LabelDate>1/1/2015</LabelDate>\n" +
                "<CustomerRefNo/>\n" +
                "<SenderName>Adam Smith</SenderName>\n" +
                "<SenderEMail>asmith@email.com</SenderEMail>\n" +
                "<RecipientName>Janice Dickens</RecipientName>\n" +
                "<RecipientEMail>jdickens@email.com</RecipientEMail>\n" +
                "<HoldForManifest/>\n" +
                "<CommercialPrice>false</CommercialPrice>\n" +
                "<InsuredAmount>425.00</InsuredAmount>\n" +
                "<Container>NONRECTANGULAR</Container>\n" +
                "<Size>LARGE</Size>\n" +
                "<Width>7</Width>\n" +
                "<Length>20.5</Length>\n" +
                "<Height>15</Height>\n" +
                "<Girth>60</Girth>\n" +
                "  </ExpressMailLabelCertifyRequest>";
        Usps usps2 = Usps.create("034I2GLO7047", "089KU88WB902");
        // Usps usps2 = Usps.create("625I2GLO1038", "506TB60WB112");   // new
//        String s1 = IOUtils.readText(Resources.getResourceAsFile("usps.xml"));
        String s1 = usps2.doCallUspsApi(serviceUrl, api, xml);
//        IOUtils.writeText(s1, new FileOutputStream("c:/usps.xml"), Charsets.UTF_8, true);
//        System.exit(0);
//        System.out.println(s1);
        // ExpressMailLabelResponse / EMLabel
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(false); // never forget this!
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new ByteArrayInputStream(Bytes.toBytes(s1)));
//        XPathFactory xPathFactory = XPathFactory.newInstance();
//        XPath xPath = xPathFactory.newXPath();
        // /ExpressMailLabelCertifyResponse/EMLabel[1]/text()[1]
        /*-效率太低
        XPathExpression imgXPath = xPath.compile("/ExpressMailLabelResponse/EMLabel/text()");
        String img = imgXPath.evaluate(doc.getDocumentElement());
        */
        System.out.println("img---------------");
        NodeList labels = doc.getDocumentElement().getElementsByTagName("EMLabel");
        if (0 < labels.getLength()) {
            String img = labels.item(0).getTextContent();
            System.out.println(img);
//            img = img.replace(" ", "");
            img = img.replace("\n", "");
            System.out.println(img);
            byte[] bytes = Base64.decode(img);
            /*
            byte[] bytes1 = new BASE64Decoder().decodeBuffer(img);
            System.out.println(Arrays.equals(bytes, bytes1));
            bytes = bytes1;
            */

            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
//            FileOutputStream fos = new FileOutputStream("c:/a.pdf");
            FileOutputStream fos = new FileOutputStream("c:/a.tif");
            IOUtils.flow(bais, fos, true, true);
                    /*
            BufferedImage read = ImageIO.read(bais);
            ImageIcon icon = new ImageIcon(read);
            JOptionPane.showMessageDialog(null, null, null, JOptionPane.YES_OPTION, icon);
            System.out.println(img);
            */
        }

        System.exit(0);


        Uspsx usps = Uspsx.create("034I2GLO7047", "089KU88WB902");
        SignatureConfirmationlRequest req = new SignatureConfirmationlRequest();
        req.setFromName("John Doe");
        req.setFromFirm("USPS");
        req.setFromAddress1("RM 2100");
        req.setFromAddress2("475 L’Enfant Plaza SW");
        req.setFromCity("Washington");
        req.setFromState("DC");
        req.setFromZip5("20260");
        req.setFromZip4("");

        req.setToName("Janice Dickens");
        req.setToFirm("XYZ Corporation");
        req.setToAddress1("Ste 100");
        req.setToAddress2("2 Massachusetts Ave NE");
        req.setToCity("Washington");
        req.setToState("DC");
        req.setToZip5("20212");
        req.setToZip4("");
        req.setWeightInOunces(10);
        req.setServiceType("Priority");

        usps.setServiceUrl("https://secure.shippingapis.com/ShippingAPI.dll");
//        usps.setServiceUrl("http://production.shippingapis.com/ShippingAPI.dll");
        // SignatureConfirmationV4 or SignatureConfirmationCertifyV4, 区别在哪里？
        String s = usps.callUspsApi("SignatureConfirmationV4", req);
        System.out.println(s);
        System.exit(0);
        /*- 地址验证
        Address addr = new Address()
                .setId("adr_1")
                .setCity("Greenbelst")
                .setState("MD")
                .setStreets(new String[]{"6406 Ivxy Lane"});

        addr = usps.verify(addr);
        System.out.println(addr.hasError());
        System.out.println(addr);
        */

        /*- 物流追踪
        TrackInfo tracker = usps.track("EF014986098US");
        System.out.println(tracker.hasError());
        if(!tracker.hasError()) {
            List<TrackEvent> details = tracker.getDetails();
            for (TrackEvent detail : details) {
                System.out.println(detail);
            }
        }
        */


        /* for 价格计算 */
        RatePackage pkg = new RatePackage();
        pkg.setId("1ST");
        pkg.setService(Service.PRIORITY_MAIL_EXPRESS_CPP);
        pkg.setFirstClassMailType(UspsFirstClassMailType.PARCEL);
        pkg.setZipOrigination("44106");
        pkg.setZipDestination("20770");
        pkg.setPounds("0");
        pkg.setOunces("3.5");
        pkg.setSize(Size.REGULAR);
//        pkg.setSize(Size.LARGE);
        pkg.setMachinable(true);

//        usps.calcRate(pkg);
        /**/

        /* ****************************************
        // 邮编查找
        addr = new Address();
        addr.setId("0");
        addr.setAddress2("8 Wildwood Drive");
        addr.setCity("Old Lyme");
        addr.setState("CT");

        usps.lookupZipCode(addr);
        */

        /* **************
        // 城市/州查找
        ZipCode zip = new ZipCode();
        zip.setId("0");
        zip.setZip5("06371");

        usps.lookupCityState(zip);
        */

        /*
        Package pkg = new Package();
        pkg.setId("0");
        pkg.setSize(Size.REGULAR);
        pkg.setService(Service.PRIORITY);
        pkg.setContainer(Container.VARIABLE);
//        pkg.setFirstClassMailType(FirstClassMailType.LETTER);
        pkg.setZipOrigination("06371");
        pkg.setZipDestination("06371");
        pkg.setPounds("0");
        pkg.setOunces("10");
        pkg.setMachinable(false);


        List<Package> pkgs = usps.calcRate(pkg);
        System.out.println(pkgs);
        */
//        USPSShippingCalculationService service = new USPSShippingCalculationServiceImpl();
//        service.setUspsUserName("034I2GLO7047");
    }
}
